package binarysearchtree;

import java.util.Arrays;

public class HashBack {
    static class Node {
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node[] array;
    public int usedSide;

    public static final float DEFAULT_LOAD_FACTOR = 0.75f;

    public HashBack() {
        array = new Node[10];
    }

    public void put(int key, int val) {
        int index = key % array.length;
        Node cur = array[index];
        while (cur != null) {
            if (cur.key == key) {
                cur.val = val;
            }
            cur = cur.next;
        }
        Node node = new Node(key,val);
        node.next = array[index];
        array[index] = node;
        usedSide++;

        if (doLoadFactor() > DEFAULT_LOAD_FACTOR) {
            resize();
        }
    }

    private void resize () {
        Node[] newArray = new Node[2*array.length];
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while (cur != null) {
                Node tmp = cur;
                int newIndex = cur.key % newArray.length;
                cur.next = newArray[newIndex];
                newArray[newIndex] = tmp;
            }
        }
        array = newArray;
    }

    private float doLoadFactor() {
        return usedSide*1.0f  / array.length;
    }

    public int get(int key) {
        int index = key % array.length;
        Node cur = array[index];
        while (cur != null) {
            if (cur.key == key) {
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }
}
